<template>
	<view class="gl-container-page gl-backgroup-full"
		style="display: flex;flex-direction: column;justify-content: space-between;">
		<view class="gl-top-font" style="color: #f3eacd;padding: 0 30px;">
			<view :style="{height: sConf.tH+'px'}"></view>
			<view style="font-size: xxx-large;">Hello!</view>
			<view style="font-size: x-large;">欢迎登录{{sConf.title}}</view>
		</view>
		<view style="padding: 0 30px;">
			<!-- 注册 -->
			<view v-if="!curState" class="gl-backgroup-rain"
				style="height: 40vh;padding: 10px 20px;border-radius: 20px 20px 0 0;display: flex;flex-direction: column;gap: 25px;">

				<view class=""
					style="display: flex;flex-direction: column;align-items: center;gap: 10px;margin-top: 10px;">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
						style="padding: 0;background-color: transparent;">
						<image :src="avatarUrl" mode="scaleToFill" style="width: 64px;height: 64px;"></image>
					</button>

					<view style="width: 100%;display: flex;justify-content: center;">
						<input v-model="avatarNam" type="nickname" placeholder="点击授权用户昵称" @input="onChooseName"
							style="text-align: center;vertical-align:middle;" />
					</view>

					<!--
					<input v-model="avatarNam" type="nickname" placeholder="点击授权用户昵称" @input="onChooseName"
						style="text-align: center;vertical-align:middle;width:100%;padding:20px 0;fontSize:large;background-color: #fff; border-radius: 20px;" />
					-->

				</view>

				<view class="">
					<tn-button shape="round" text-color="#70552d" bg-color="#f1f1f1" open-type="getPhoneNumber" debounce
						@getphonenumber="onRegeditUserinfo"
						:custom-style="{width:'100%',padding:'15px 0',fontSize:'large'}">手机注册</tn-button>
				</view>
				<view class=""
					style="color: #f3eacd;font-size: small;display: flex;justify-content: center;align-items: center;">
					<text>已有账号? <text style="font-weight: bold;" @tap="()=>{this.curState = true}"> 登录</text></text>
				</view>

				<view style="padding: 40px 0;">
					<label v-if="avatarUrl.includes('default/default')" for="">点击授权用户头像</label>
				</view>
			</view>


			<!-- 登录 -->
			<view v-else class="gl-backgroup-rain"
				style="height: 40vh;padding: 10px 20px;border-radius: 20px 20px 0 0;display: flex;flex-direction: column;gap: 25px;">
				<view class="" style="width: 100%;display: flex;justify-content: center;">
					<image src="https://cos.yuejunxi.com/media/v2/logo.png" mode="" style="width: 142px;height: 48px;">
					</image>
				</view>
				<view class="">
					<!-- eventWxLogon -->
					<tn-button text-color="#70552d" bg-color="#f1f1f1" @click="eventWxLogon" debounce
						:custom-style="{width:'100%',padding:'5px 0',fontSize:'large'}">
						<template #default>
							<view style="display: flex;align-items: center;gap: 10px;">
								<tn-icon name="wechat-fill" size="64" :custom-style="{padding:'0'}"></tn-icon>
								<text>微信快捷登录</text>
							</view>
						</template>
					</tn-button>
				</view>
				<view class="">
					<tn-button text-color="#70552d" bg-color="#f1f1f1" open-type="getPhoneNumber" debounce
						:disabled="!agent" :custom-style="{width:'100%',padding:'9px 0',fontSize:'large'}"
						@getphonenumber="eventPhoneLogin">
						<template #default>
							<view style="display: flex;align-items: center;gap: 10px;">
								<tn-icon name="phone-fill" size="48" :custom-style="{padding:'0'}"></tn-icon>
								<text>手机快捷登录</text>
							</view>
						</template>
					</tn-button>
				</view>
				<view v-if="false" class=""
					style="color: #f3eacd;display: flex;justify-content: space-around;align-items: center;">
					<text>注册账号</text>
					<text>忘记密码</text>
				</view>

			</view>
		</view>
		<view class="">
			<view class=""
				style="color: #f3eacd;font-size: small;display: flex;justify-content: center;align-items: center;">
				<tn-checkbox v-model="agent" active-color="#70552d" checked-shape="circle"
					style="padding: 15px;"></tn-checkbox>
				<text>同意</text>
				<text @tap="()=>{this.showSecret = true}">《用户协议》</text>
				<text @tap="()=>{this.showSecret = true}">《隐私协议》</text>
			</view>
			<view
				style="color: #f3eacd;font-size: small;display: flex;justify-content: center;align-items: center;gap: 10px;">
				<text>ver: {{sConf.ver}}</text>
				<text>{{sConf.scene}}</text>
			</view>
		</view>


		<!-- popup弹窗 -->
		<tn-popup v-model="showSecret" open-direction="bottom" :overlay-closeable="false">
			<tn-switch-tab v-model="curConcert" :tabs="['用户协议', '隐私声明']">
				<subSecretCardVue v-if="curConcert === 0" src="/api/doc/" @eventClose="()=>{this.showSecret = false}"
					@eventAgree="eventAgree">
				</subSecretCardVue>
				<subSecretCardVue v-if="curConcert === 1" src="/api/dod/" @eventClose="()=>{this.showSecret = false}"
					@eventAgree="eventAgree">
				</subSecretCardVue>
			</tn-switch-tab>
			<view class="" style="padding: 20px;">
				<button open-type="agreePrivacyAuthorization" @agreeprivacyauthorization="eventAgree"
					style="background-color: #000;color: #fff;">接受协议</button>
			</view>
		</tn-popup>
	</view>
</template>

<script>
	import utils from '@/common/utils.js'
	import psMethod from '@/common/psMethod';
	import UniToCos from '@/js_sdk/com-ls-cos/components/ls-cos'
	import subSecretCardVue from '@/components/sub-secret-card/sub-secret-card.vue';
	export default {
		data() {
			return {
				sConf: getApp().globalData,
				parent: null, // 推荐用户
				curState: true, // 是否已绑定手机
				agent: false, // 同意协议
				showSecret: false, // 显示协议
				curConcert: 0,
				loging: 0, // 等待任务中
				curPhone: null,
				curIdx: null,
				curCode: null,
				rtCodeCSS: {
					position: 'absolute',
					top: '7px',
					right: '5px',
					padding: '10px'
				},
				avatarUrl: 'https://cos.yuejunxi.com/media/default/default_0.png',
				avatarNam: null,
				isNotReg: true,
				navPage: '/pages/index/index'
			}
		},
		onLoad(query) {
			console.log('onLoad', 'login');
			let parent = Number(query.staff) || null;
			if (Boolean(parent)) {
				this.parent = parent
			}
			let navPage = String(query.url) || null;
			if (Boolean(navPage) && navPage === 'index') {
				this.navPage = '/pages/index/index'
			}
			if (Boolean(navPage) && navPage === 'product') {
				this.navPage = '/pagec/product/product'
			}
		},
		onReady() {
			console.log('onReady', 'login');
		},
		onShow() {
			console.log('onShow', 'login');
			console.log('全局用户->', this.sConf);
			console.log('全局用户->', this.sConf.auth);

			this.autoLoginCache().then(res => {
				this.sConf.token = res.resmsg.token;
				this.sConf.auth = res.resmsg.auth;
				console.log('111全局用户->', this.sConf.auth);
				// 检测绑定推荐
				if (Boolean(this.parent) && !Boolean(this.sConf.auth.parent)) {
					console.log('检测绑定推荐', false);
					this.bindParentStaff(this.parent)
				}

				// 跳转首页
				this.$nextTick(() => {
					uni.redirectTo({
						url: this.navPage
					});
				})
			}).catch(err => {
				let that = this
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success(code) {
						console.log('wxLogin->', code);
						let host = that.sConf.host + '/weapps/login/'
						let data = {
							code: code.code
						}
						console.log('kwargs->', data);
						psMethod.requestPostSync(host, data).then(res => {
							console.log('用户登录成功->', res);
							// 写入口令
							that.sConf.token = res.resmsg.token;
							that.sConf.auth = res.resmsg.auth;
							console.log('222全局用户->', that.sConf.auth);

							// 检测绑定推荐
							if (Boolean(that.parent) && !Boolean(that.sConf.auth.parent)) {
								console.log('检测绑定推荐', false);
								that.bindParentStaff(that.parent)
							}

							// 跳转首页
							that.$nextTick(() => {
								uni.redirectTo({
									url: that.navPage
								});
							})
						})
					}
				});
			})

			console.log('000全局用户->', this.sConf.auth);

		},
		components: {
			subSecretCardVue
		},
		methods: {
			/**
			 * 新登录
			 */
			async waitLogin() {
				// 检测自动登录
				let logined = await this.autoLoginCache().then(res => {
					this.sConf.token = res.resmsg.token;
					this.sConf.auth = res.resmsg.auth;
				}).catch(err => {
					let that = this
					uni.login({
						provider: 'weixin',
						onlyAuthorize: true,
						success(code) {
							console.log('wxLogin->', code);
							let host = that.sConf.host + '/weapps/login/'
							let data = {
								code: code.code
							}
							console.log('kwargs->', data);
							psMethod.requestPostSync(host, data).then(res => {
								console.log('用户登录成功->', res);
								// 写入口令
								that.sConf.token = res.resmsg.token;
								that.sConf.auth = res.resmsg.auth;
							})
						}
					});
				})

			},
			/**
			 * 检测自动登录
			 */
			autoLoginCache() {
				console.log('__检测自动登录__');
				return new Promise((resolve, reject) => {
					try {
						let prefix = this.sConf.run === 'trial' ? 'dev' : ''
						let stamp = Date.now();
						let token = uni.getStorageSync(prefix + 'token');
						let auth = uni.getStorageSync(prefix + 'auth');
						let last = uni.getStorageSync(prefix + 'last');
						if (token && auth && ((stamp - last) < 10 * 3600 * 1000)) {
							console.log('login__检测自动登录', true);
							resolve({
								'rescode': 201,
								'resmsg': {
									'token': token,
									'auth': auth
								}
							})
						} else {
							console.log('login__检测自动登录', false);
							uni.clearStorageSync();
							reject(false)
						}
					} catch (e) {
						//TODO handle the exception
						console.log('加载本地缓存失败', e);
						reject(false)
					}
				})
			},
			/**
			 * 绑定推荐
			 */
			bindParentStaff(e) {
				if (!Boolean(this.sConf.auth.parent) && Boolean(e) && this.sConf.auth.id !== e) {
					let host = this.sConf.host + '/weapps/bindHelp/';
					let token = this.sConf.token || ''
					let data = {
						parent: e
					}
					utils.authenticatorOnPost(host, token, data).then(res => {
						console.log('绑定推荐', res);
					})
				}
			},

			eventToReg() {
				this.curState = false;
			},


			/**
			 * 跳转到首页
			 */
			navIndex() {
				let prefix = this.sConf.run === 'trial' ? 'dev' : ''
				try {
					uni.setStorageSync(prefix + 'token', this.sConf.token);
					uni.setStorageSync(prefix + 'auth', this.sConf.auth);
					uni.setStorageSync(prefix + 'last', Date.now());
				} catch (e) {
					console.log('写入本地缓存失败');
				}
				this.$nextTick(() => {
					uni.redirectTo({
						url: this.navPage
					});
				})
			},

			/**
			 * 倒计时
			 */
			waitTimeout() {
				let that = this
				that.loging = 60
				let timer = setInterval(() => {
					if (that.loging > 0) {
						that.loging--
					} else {
						console.log('over');
						clearInterval(timer)
					}
				}, 1000)
			},



			/**
			 * 登录回调
			 */
			async eventLogin(e) {
				console.log('eventLogin', e);
				this.sConf.token = e.resmsg.token;
				this.sConf.auth = e.resmsg.auth;

				await this.bindParentStaff(this.parent)

				if (!Boolean(e.resmsg.auth.phone)) {
					this.curState = false
				} else {
					this.navIndex()
				}

			},
			/**
			 * 微信登录
			 */
			async eventWxLogon() {
				// console.log('eventWxLogon', e);
				// this.avatarUrl = e.target.avatarUrl
				// return
				if (!this.agent) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						title: '请同意用户协议'
					})
					return
				}
				this.navIndex()
				// return
				// uni.showLoading({
				// 	title: '正在登录'
				// })
				// let code = await uni.login({
				// 	provider: 'weixin',
				// 	onlyAuthorize: true,
				// });
				// let host = this.sConf.host + '/weapps/login/'
				// let data = {
				// 	code: code.code
				// }
				// await psMethod.requestPostSync(host, data).then(res => {
				// 	console.log('用户登录成功', res);
				// 	this.eventLogin(res)
				// }).catch(err => {
				// 	console.log('用户登录失败', err);
				// 	uni.showModal({
				// 		title: '登录失败',
				// 		content: err.resmsg,
				// 		showCancel: false
				// 	})
				// }).finally(() => {
				// 	uni.hideLoading()
				// })

			},
			/**
			 * 手机登录
			 */
			async eventPhoneLogin(e) {
				if (!this.agent) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						title: '请同意用户协议'
					})
					return
				}
				if (!e.detail.code) {
					return
				}
				uni.showLoading({
					title: '正在登录'
				})
				console.log('eventPhoneLogin', e.detail.code);
				let host = this.sConf.host + '/weapps/phone/'
				let data = {
					code: e.detail.code,
					sid: this.sConf.auth.id
				}
				psMethod.requestPostSync(host, data).then(res => {
					console.log('手机登录成功', res);
					this.sConf.token = res.resmsg.token;
					this.sConf.auth = res.resmsg.auth;
					this.navIndex()

					// this.eventLogin(res)
				}).catch(err => {
					console.log('手机登录失败', err);
					uni.showModal({
						title: '登录失败',
						content: err.resmsg,
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 请求直接短信
			 */
			eventSms(e) {
				console.log('eventSms', this.curPhone);
				if (!this.agent) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						title: '请同意用户协议'
					})
					return
				}
				if (!this.curPhone) {
					uni.showToast({
						title: '请输入手机号码'
					})
					return
				}

				let host = this.sConf.host + '/api/sendSms/'
				let data = {
					phone: this.curPhone,
					valited: e
				}
				psMethod.requestPostSync(host, data).then(res => {
					console.log('请求验证码', res);
					this.curIdx = res.resmsg
				}).catch(err => {
					uni.showToast({
						title: '请求验证码失败'
					})
				}).finally(() => {
					this.waitTimeout()
				})
			},
			/**
			 * 绑定手机
			 */
			eventBindPhone() {
				if (!this.agent) {
					// #ifdef MP-WEIXIN
					wx.vibrateShort();
					// #endif
					uni.showToast({
						title: '请同意用户协议'
					})
					return
				}
				if (!this.curPhone || !this.curIdx || !this.curCode) {
					uni.showToast({
						title: '请填入短信验证码'
					})
					return
				}
				let host = this.sConf.host + '/api/bindSms/'
				let token = this.sConf.token || ''
				let data = {
					phone: this.curPhone,
					captcha: this.curCode,
					recode: this.curIdx,
					grant_type: 'newUser'
				}
				psMethod.authenticatorPostSync(host, token, data).then(res => {
					console.log('绑定成功', res);
					let that = this
					uni.showModal({
						title: '注册成功',
						content: '成功注册账户，是否需要登录?',
						success(r) {
							if (r.confirm) {
								that.navIndex()
							}
						}
					})
				}).catch(err => {
					console.log('绑定失败', err);
					uni.showToast({
						title: '绑定失败'
					})
				})
			},
			/**
			 * 短信登录
			 */
			eventLoginPhone() {
				if (!this.curPhone || !this.curIdx || !this.curCode) {
					uni.showToast({
						title: '请填入短信验证码'
					})
					return
				}
				let host = this.sConf.host + '/api/bindSms/'
				let token = this.sConf.token || ''
				let data = {
					phone: this.curPhone,
					captcha: this.curCode,
					recode: this.curIdx,
					grant_type: 'allUser'
				}
				psMethod.authenticatorPostSync(host, token, data).then(res => {
					console.log('绑定成功', res);
					this.navIndex()
				}).catch(err => {
					console.log('绑定失败', err);
					uni.showToast({
						title: '绑定失败'
					})
				})
			},
			/**
			 * 注册手机用户
			 */
			async onRegeditUserinfo(e) {
				console.log('onRegeditUserinfo', e);
				if (this.avatarUrl.includes('default.png')) {
					uni.showModal({
						title: '错误',
						content: '请点击头像图标授权',
						showCancel: false
					})
					return
				}
				if (this.avatarNam.length === 0 || this.avatarNam === '新用户') {
					uni.showModal({
						title: '错误',
						content: '请点击昵称授权',
						showCancel: false
					})
					return
				}


				uni.showLoading({
					title: '正在注册'
				})
				console.log('eventPhoneLogin', e.detail.code);
				let host = this.sConf.host + '/weapps/phone/'
				let data = {
					code: e.detail.code,
					face: this.sConf.auth.face,
					name: this.avatarNam,
					sid: this.sConf.auth.id
				}

				if (this.avatarUrl !== 'https://cos.yuejunxi.com' + this.sConf.auth.face) {
					console.log('new face', this.avatarUrl, this.sConf.auth.face);
					let cosDict = await this.getUploadCos().then(res => {
						return res
					})
					console.log('image ->', cosDict);
					let images = await this.cosUploadFile(cosDict, this.avatarUrl)
					console.log('上传到cos ->', images);
					data['face'] = images
				}

				psMethod.requestPostSync(host, data).then(res => {
					console.log('手机登录成功', res);
					this.sConf.token = res.resmsg.token;
					this.sConf.auth = res.resmsg.auth;
					this.navIndex()
				}).catch(err => {
					console.log('手机登录失败', err);
					uni.showModal({
						title: '登录失败',
						content: err.resmsg,
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 同意用户协议
			 */
			eventAgree(e) {
				console.log('eventAgree', e);
				this.agent = true
				this.showSecret = false
			},
			/**
			 * 加载用户头像昵称
			 */
			onChooseAvatar(e) {
				console.log('onChooseAvatar', e);
				this.avatarUrl = e.detail.avatarUrl
				if (this.avatarUrl.includes('default.png') || !this.avatarNam || this.avatarNam.length === 0) {
					this.isNotReg = true
				} else {
					this.isNotReg = false
				}
			},
			onChooseName(e) {
				console.log('onChooseName', e);
				this.avatarNam = e.detail.value
				if (this.avatarUrl.includes('default.png') || !this.avatarNam || this.avatarNam.length === 0) {
					this.isNotReg = true
				} else {
					this.isNotReg = false
				}
			},
			/**
			 * 上传图片
			 */
			getUploadCos() {
				console.log('加载cos参数');
				return new Promise((resolve, reject) => {
					uni.request({
						url: this.sConf.host + '/api/cosSt/',
						method: 'POST',
						header: {
							'content-type': 'application/json',
							'authorization': this.sConf.token
						},
						data: {},
						success(res) {
							resolve(res.data.resmsg)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			cosUploadFile(cosDict, file) {
				// 传入bucket和region
				let cos = new UniToCos(cosDict.account.bucket, cosDict.account.region)
				// 传入secretId,secretKey,sessionToken
				cos.createCos(cosDict.credentials.tmpSecretId, cosDict.credentials.tmpSecretKey, cosDict.credentials
					.sessionToken)
				// 传入filePath和fileName
				let filePath = file;
				let fileName = 'media/face/' + this.sConf.auth.id + '.jpg';

				return new Promise((resolve, reject) => {
					cos.wxUploadFile(filePath, fileName).then(res => {
						console.log("上传图片", res.Location.substr(res.Location.indexOf('/')))
						resolve(res.Location.substr(res.Location.indexOf('/')))
					}).catch(err => {
						reject(err)
					})
				})

			},
		}
	}
</script>

<style lang="scss" scoped></style>